package handler

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"lucidity.note/app/common"
	"lucidity.note/app/common/bean"
	"lucidity.note/app/service"
)

func RegisterNoteBookRouter(router *gin.Engine) {
	group := router.Group("/notebook")
	{
		group.POST("/new", newNotebookHandler)
		group.GET("/all", getAllNotebookHandler)
		group.GET("/:notebookid", getNotebookByIdHandler)
		group.PUT("/update", updateNotebookHandler)
	}
}

// 新建笔记本
func newNotebookHandler(ctx *gin.Context) {
	var notebook bean.Notebook
	response := &bean.ResponseParam{}
	if err := ctx.ShouldBind(&notebook); nil != err {
		response.Failure(fmt.Sprintf("新建笔记本失败: 绑定参数失败，错误详情{%s}", err.Error()))
	} else {
		service := &service.NotebookService{}
		if err := service.NewNotebookService(&notebook); nil != err {
			response.Failure(err.Error())
		} else {
			response.Data = &notebook
			response.Succeed(fmt.Sprintf("笔记本[%s]创建成功", notebook.Name))
		}
	}
	ctx.JSON(response.Status, response)
}

// 查询所有的笔记本信息
func getAllNotebookHandler(ctx *gin.Context) {
	response := &bean.ResponseParam{}
	service := &service.NotebookService{}
	if notebooks, err := service.GetAllNotebookService(); nil != err {
		response.Failure(err.Error())
	} else {
		response.Data = notebooks
		response.Succeed(fmt.Sprintf("查询所有笔记本成功，共 %d 个笔记本", len(notebooks)))
	}
	ctx.JSON(response.Status, response)
}

// 根据笔记本ID查询笔记本
func getNotebookByIdHandler(ctx *gin.Context) {
	response := &bean.ResponseParam{}
	id := ctx.Param("notebookid")
	if common.IsBlank(id) {
		response.Failure("当前笔记本ID为空，无法查找对应的笔记本")
	} else {
		service := &service.NotebookService{}
		if notebook, err := service.GetNotebookByIdService(id); nil != err {
			response.Failure(err.Error())
		} else {
			response.Data = notebook
			response.Succeed(fmt.Sprintf("查询[id=%s]的笔记本成功", notebook.ID))
		}
	}
	ctx.JSON(response.Status, response)
}

// 更新笔记本信息
func updateNotebookHandler(ctx *gin.Context) {
	var notebook bean.Notebook
	response := &bean.ResponseParam{}
	if err := ctx.ShouldBind(&notebook); nil != err {
		response.Failure(fmt.Sprintf("更新笔记本失败: 绑定参数失败，错误详情{%s}", err.Error()))
	} else {
		service := &service.NotebookService{}
		if err := service.UpdateNotebookService(&notebook); nil != err {
			response.Failure(err.Error())
		} else {
			response.Data = &notebook
			response.Succeed(fmt.Sprintf("笔记本[%s]更新成功", notebook.Name))
		}
	}
	ctx.JSON(response.Status, response)
}
